import 'package:fate_blind_box/network/Api.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/utils/common_widget.dart';
import 'package:fate_blind_box/utils/loading.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:fate_blind_box/utils/snack_bar.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import '../../../widget/icon_text.dart';
import '../../main/navigator.dart';

class ProfileCompleteUi extends StatefulWidget {
  const ProfileCompleteUi({Key? key}) : super(key: key);

  @override
  State<ProfileCompleteUi> createState() => _ProfileCompleteUiState();
}

class _ProfileCompleteUiState extends State<ProfileCompleteUi> {
  int _gender = 2;
  String _avatarFilePath = "";
  final _nickController = TextEditingController();
  final _birthdayController = TextEditingController();
  final _codeController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    final screenWidth = size.width;
    return AppWidget.navTitleBar(
      title: "完善资料",
      bgColor: Colors.white,
      childWidget: SingleChildScrollView(
        child: Column(
          children: [
            // 头像
            Container(
                margin: const EdgeInsets.only(top: 24),
                child: Center(
                    child: GestureDetector(
                  onTap: () {
                    _checkAvatar();
                  },
                  child: Stack(
                    children: [
                      ClipOval(
                        child: _avatarFilePath.isEmpty
                            ? Image.asset("images/ic_dtx.png",
                                width: 80, height: 80, fit: BoxFit.cover)
                            : Image.network(_avatarFilePath,
                                width: 80, height: 80, fit: BoxFit.cover),
                      ),
                      Positioned(
                          right: 0,
                          bottom: 0,
                          width: 20,
                          height: 20,
                          child: CircleAvatar(
                            backgroundColor: ThemeColor.textColor,
                            child: const Icon(
                              Icons.photo_camera,
                              color: Colors.white,
                              size: 10,
                            ),
                          ))
                    ],
                  ),
                ))),
            // tip
            Container(
                margin: const EdgeInsets.only(top: 10),
                child: Text(
                  "上传真实的头像好处多多～",
                  style: TextStyle(
                      color: ThemeColor.textColorSecond, fontSize: 12),
                )),
            // 昵称
            Container(
              margin: const EdgeInsets.only(top: 20, left: 12, right: 12),
              height: 50,
              decoration: BoxDecoration(
                  border: Border(
                      bottom: BorderSide(
                          color: ThemeColor.dividerColor, width: 1))),
              child: Row(
                children: [
                  Container(
                    width: 50,
                    height: 50,
                    alignment: const Alignment(1, 0),
                    child: Text("昵称",
                        style: TextStyle(color: ThemeColor.textColorSecond)),
                  ),
                  Container(
                      margin: const EdgeInsets.only(left: 28),
                      height: 50,
                      width: screenWidth - 102,
                      child: TextField(
                        controller: _nickController,
                        maxLength: 16,
                        keyboardType: TextInputType.text,
                        cursorColor: ThemeColor.mainColor,
                        style: TextStyle(
                            color: ThemeColor.textColor, fontSize: 14),
                        decoration: InputDecoration(
                            border: InputBorder.none,
                            counterText: "",
                            hintText: "请输入",
                            hintStyle: TextStyle(
                                color: ThemeColor.textColorSecond,
                                fontSize: 14)),
                      ))
                ],
              ),
            ),
            // 性别
            Container(
              margin: const EdgeInsets.symmetric(horizontal: 12),
              height: 50,
              decoration: BoxDecoration(
                  border: Border(
                      bottom: BorderSide(
                          color: ThemeColor.dividerColor, width: 1))),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Container(
                    width: 50,
                    height: 50,
                    alignment: const Alignment(1, 0),
                    child: Text("性别",
                        style: TextStyle(color: ThemeColor.textColorSecond)),
                  ),
                  GestureDetector(
                    onTap: () {
                      setState(() {
                        _gender = 2;
                      });
                    },
                    child: Container(
                      width: 36,
                      height: 16,
                      margin: const EdgeInsets.only(left: 28),
                      alignment: Alignment.center,
                      decoration: ShapeDecoration(
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(8)),
                          color: _gender == 2
                              ? ThemeColor.mainColor
                              : ThemeColor.checkNormalColor),
                      child: const IconText(
                        "女",
                        icon: Icon(
                          Icons.female,
                          color: Colors.white,
                          size: 10,
                        ),
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 10,
                        ),
                      ),
                    ),
                  ),
                  GestureDetector(
                    onTap: () {
                      setState(() {
                        _gender = 1;
                      });
                    },
                    child: Container(
                      width: 36,
                      height: 16,
                      margin: const EdgeInsets.only(left: 20),
                      alignment: Alignment.center,
                      decoration: ShapeDecoration(
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(8)),
                          color: _gender == 1
                              ? ThemeColor.mainColor
                              : ThemeColor.checkNormalColor),
                      child: const IconText(
                        "男",
                        icon: Icon(
                          Icons.male,
                          color: Colors.white,
                          size: 10,
                        ),
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 10,
                        ),
                      ),
                    ),
                  ),
                  Container(
                    margin: const EdgeInsets.only(left: 18),
                    child: Text(
                      "（性别提交后将无法修改）",
                      style: TextStyle(
                          color: ThemeColor.textColorSecond, fontSize: 12),
                    ),
                  )
                ],
              ),
            ),
            // 生日
            Container(
              margin: const EdgeInsets.symmetric(horizontal: 12),
              height: 50,
              decoration: BoxDecoration(
                  border: Border(
                      bottom: BorderSide(
                          color: ThemeColor.dividerColor, width: 1))),
              child: Row(
                children: [
                  Container(
                    width: 50,
                    height: 50,
                    alignment: const Alignment(1, 0),
                    child: Text("生日",
                        style: TextStyle(color: ThemeColor.textColorSecond)),
                  ),
                  Container(
                      margin: const EdgeInsets.only(left: 28),
                      height: 50,
                      width: screenWidth - 102,
                      child: TextField(
                        readOnly: true,
                        onTap: () async {
                          final date = await showDatePicker(
                              context: context,
                              initialDate: DateTime.parse("1980-01-01"),
                              firstDate: DateTime.parse("1960-01-01"),
                              lastDate: DateTime.now());
                          _birthdayController.text =
                              date.toString().split(" ")[0];
                        },
                        controller: _birthdayController,
                        maxLength: 16,
                        keyboardType: TextInputType.text,
                        cursorColor: ThemeColor.mainColor,
                        style: TextStyle(
                            color: ThemeColor.textColor, fontSize: 14),
                        decoration: InputDecoration(
                            border: InputBorder.none,
                            counterText: "",
                            hintText: "请选择",
                            hintStyle: TextStyle(
                                color: ThemeColor.textColorSecond,
                                fontSize: 14)),
                      ))
                ],
              ),
            ),
            // 邀请码
            Container(
              margin: const EdgeInsets.symmetric(horizontal: 12),
              height: 50,
              decoration: BoxDecoration(
                  border: Border(
                      bottom: BorderSide(
                          color: ThemeColor.dividerColor, width: 1))),
              child: Row(
                children: [
                  Container(
                    width: 50,
                    height: 50,
                    alignment: const Alignment(1, 0),
                    child: Text("邀请码",
                        style: TextStyle(color: ThemeColor.textColorSecond)),
                  ),
                  Container(
                      margin: const EdgeInsets.only(left: 28),
                      height: 50,
                      width: screenWidth - 102,
                      child: TextField(
                        controller: _codeController,
                        maxLength: 16,
                        keyboardType: TextInputType.text,
                        cursorColor: ThemeColor.mainColor,
                        style: TextStyle(
                            color: ThemeColor.textColor, fontSize: 14),
                        decoration: InputDecoration(
                            border: InputBorder.none,
                            counterText: "",
                            hintText: "选填",
                            hintStyle: TextStyle(
                                color: ThemeColor.textColorSecond,
                                fontSize: 14)),
                      ))
                ],
              ),
            ),
            // 提交按钮
            GestureDetector(
              onTap: () {
                _submit();
              },
              child: Container(
                margin: const EdgeInsets.fromLTRB(18, 120, 18, 72),
                decoration: ShapeDecoration(
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(24)),
                    color: ThemeColor.mainColor),
                height: 48,
                alignment: Alignment.center,
                child: const Text(
                  "完成",
                  style: TextStyle(fontSize: 16, color: Colors.white),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  /// 打开相册
  _checkAvatar() {
    loading(() async {
      final picker = ImagePicker();
      final pickerFile = await picker.pickImage(source: ImageSource.gallery);
      if (pickerFile != null) {
        final res = await Api.getInstance()
            .uploadAvatar(Provider.memberId, pickerFile.path);
        print(res);
        if (res['code'] == 0) {
          setState(() {
            _avatarFilePath = res['data']['url'];
          });
        } else {
          ThemeSnackBar.show(context, res['msg']);
          toast(res['msg']);
        }
      }
    });
  }

  /// 提交
  _submit() {
    if (_avatarFilePath.isEmpty ||
        _nickController.text.isEmpty ||
        _birthdayController.text.isEmpty) {
      return;
    }
    loading(() async {
      final res = await Api.getInstance().completeUserInfo(
          Provider.memberId,
          _avatarFilePath,
          _nickController.text,
          _gender,
          _birthdayController.text,
          _codeController.text,
          Provider.loginSign);
      if (res['code'] == 0) {
        Navigator.of(context)
            .push(MaterialPageRoute(builder: (ctx) => AppMain()));
      } else {
        ThemeSnackBar.show(context, res['msg']);
      }
    });
  }
}
